const express = require('express')
const router = express.Router()
const path = require('path')
const multer = require('multer')
const UserModel = require(path.join(process.cwd(), '/models/UserModel'))
const checkTokenMiddleware = require(path.join(process.cwd(), '/middlewares/checkTokenMiddleware'))

// 设置 multer 存储
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })

// 上传图片
router.post('/avatar', checkTokenMiddleware, upload.single('file'), async (req, res) => {
  try {
    const newAvatar = await UserModel.create({
      avatar: req.file.buffer,
      contentType: req.file.mimetype
    })
    await newAvatar.save()
    return res.sendResult(newAvatar._id, 200, '上传成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 获取图片
router.get('/avatar/:uId', checkTokenMiddleware, async (req, res) => {
  try {
    const data = await UserModel.findById(req.params.uId)
    if (!data) return res.sendResult(null, 404, '图片未找到')
    res.set('Content-Type', data.contentType)
    res.send(data.avatar)
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 修改图片
router.put('/avatar/:uId', checkTokenMiddleware, upload.single('file'), async (req, res) => {
  try {
    const avatar = await UserModel.findOneAndUpdate(
      { _id: req.params.uId },
      {
        avatar: req.file.buffer,
        contentType: req.file.mimetype
      },
      { new: true }
    )
    if (!avatar) return res.sendResult(null, 404, '图片未找到')
    return res.sendResult({ userID: avatar._id }, 200, '修改成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

module.exports = router
